"""Read CEL

.. helpdoc::
Read in collections of CEL files from a directory into the Red-R session.

"""

"""<widgetXML>
    <name>Read CEL<!-- [REQUIRED] title --></name>
    <icon>default.png</icon>
    <tags>
        <tag>Affy</tag>
    </tags>
    <summary>Read in collections of CEL files from a directory into the Red-R session.<!-- [REQUIRED] A Brief description of the widget and what it does--></summary>
    <author>
        <authorname>Kyle R Covington</authorname>
        <authorcontact>kyle@red-r.org</authorcontact>
    </author>
</widgetXML>
"""

"""
<name>Read CEL Files</name>
<description>Allows the user to pick CEL files either individually or through a .txt file and outputs the eSet as an R.object</description>
<tags>Affy Files</tags>
<RFunctions>affy:ReadAffy,affy:justRMA</RFunctions>
<icon>readcel.png</icon>
<priority>10</priority>
<inputWidgets></inputWidgets>
<outputWidgets>affy_affyNormalize, affy_plotAffy, affy_RedRAffyRNADeg</outputWidgets>
"""

from OWRpy import *
#import OWGUI
import redRGUI, os
import signals, globalData
import libraries.affy.signalClasses.RAffyBatch as rab
from libraries.base.qtWidgets.fileNamesComboBox import fileNamesComboBox as redRFileNamesComboBox
from libraries.base.qtWidgets.groupBox import groupBox as redRGroupBox
from libraries.base.qtWidgets.radioButtons import radioButtons as redRRadioButtons
from libraries.base.qtWidgets.button import button as redRButton
from libraries.base.qtWidgets.commitButton import commitButton as redRCommitButton
class ReadCEL(OWRpy):
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        self.require_librarys(['affy'])
        self.path = os.path.abspath('/')
        self.methodcombo = 0
        
        
        #set R variable names
        self.setRvariableNames(['affyBatch','folder', 'cm'])
        #signals
        
        """.. rrsignals::"""
        self.outputs.addOutput('ab', "Affy Batch Object", rab.RAffyBatch)
        
        #GUI
        box = redRGroupBox(self.controlArea, "Select Folder",orientation='horizontal')
        #sizePolicy=QSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed))
        
        self.filecombo = redRFileNamesComboBox(box, label = 'File Name', displayLabel = False)
        #self.filecombo.setCurrentIndex(0)
        button = redRButton(box, 'Browse', callback = self.browseFile)
        
        self.numArrays = redRRadioButtons(self.controlArea, label = 'Number of arrays', 
        buttons = ['Less than 40', 'More than 40'],setChecked='Less than 40', orientation='horizontal')

        button2 = redRCommitButton(self.bottomAreaRight, 'Process Folder', callback = self.process)
        
    def browseFile(self): 
        fn = QFileDialog.getExistingDirectory(self, "CEL Directory", self.path)
        
        #print unicode(fn)
        if fn.isEmpty(): return
        self.filecombo.addFile(unicode(fn))
        self.saveGlobalSettings()

        
    def process(self):
        dir = self.filecombo.getCurrentFile()
        if not dir:
            return
        self.status.setText("Your data is processing")
        if self.numArrays.getChecked() == 'Less than 40':
            self.R(self.Rvariables['affyBatch']+'<-ReadAffy(celfile.path="'+dir+'")','setRData', wantType = 'NoConversion')
            self.status.setText("Your data has been processed with ReadAffy.")
        else:
            self.status.setText("This may take several minutes")
            self.R(self.Rvariables['affyBatch']+'<-justRMA(celfile.path='+self.Rvariables['folder']+')','setRData', wantType = 'NoConversion')
            self.status.setText("Data preprocessed with justRMA.")
        self.R(self.Rvariables['cm']+'<-list()', wantType = 'NoConversion') # in this case the cm should be the colnames, not the rownames as is usual
        self.sendMe()
        
    
    def sendMe(self):
        chipType = self.R('annotation('+self.Rvariables['affyBatch']+')')
        globalData.setGlobalData(self,'chipType',chipType,description='Chip Type')
        out2 = rab.RAffyBatch(self, data = unicode(self.Rvariables['affyBatch']))
        self.rSend("ab", out2)
